package com.itheima.security;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.service.UserService;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;

import com.itheima.utils.HealthStringUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @description: SpringSecurity
 * @author: wangjingliang
 * @create: 2019-11-24 08:57
 **/
@Component
public class SpringSecurityUserService implements UserDetailsService {
    @Reference
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if(HealthStringUtils.isEmpty(username)){
            return null;
        }
        //查询用户是否存在
        User user=userService.selectByUsername(username);
        //判断user是否存在
        if (user==null){
            return null;
        }
        //如果存在,则将授权和角色存储到List集合中
        List<GrantedAuthority> list=new ArrayList<>();
        //获取角色
        Set<Role> roles = user.getRoles();
        for (Role role : roles) {
            //添加角色
            list.add(new SimpleGrantedAuthority(role.getKeyword()));
            Set<Permission> permissions = role.getPermissions();
            for (Permission permission : permissions) {
                //添加权限
                list.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }

        UserDetails userDetails=new org.springframework.security.core.userdetails.User(username,user.getPassword(),list);

        return userDetails;
    }
}
